package org.forum.dao.impl;

import java.util.List;

import org.forum.dao.MainTopicDao;
import org.forum.dao.base.BaseDaoImpl;
import org.forum.domain.Forum;
import org.forum.domain.MainTopic;
import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MainTopicDaoImpl extends BaseDaoImpl<MainTopic> implements MainTopicDao {
	
	Logger logger = LoggerFactory.getLogger(MainTopicDaoImpl.class);

	@Override
	public MainTopic getAnnouncementInfoByForumId(int forumId) {
		logger.debug("forumId:" + forumId);
		String hql = "SELECT en FROM MainTopic en WHERE en.forum.forumId=?0 AND en.isAnnouncement=?1 ORDER BY addTime";
		List<MainTopic> mainTopics = (List<MainTopic>)find(hql,forumId,Boolean.TRUE);
		logger.debug("mainTopics.size:" + mainTopics.size());
		if(mainTopics.size() != 0){
			return mainTopics.get(0);
		}else{
			return null;
		}
	}

	@Override
	public List<MainTopic> getMainTopicsByForumId(int forumId, int pageNo_3, int pageSize) {
		String hql = "SELECT en FROM forum WHERE forumId=" + forumId;
		return findByPage(hql, pageNo_3, pageSize);
	}

	@Override
	public void getRepliesByMainTopicId(int mainTopicId) {}

	@Override
	public List<MainTopic> getMainTopicsByClassification(String classification, int pageN, int pageSize,String sortBy){
		String hql = "SELECT en FROM MainTopic en WHERE en.classification=?0 ORDER BY ?1";
		return findByPage(hql,pageN,pageSize,classification,sortBy);
	}

	@Override
	public List<MainTopic> getMainTopicsDirectly(int pageN, int pageSize, String sortBy) {
		String hql = "SELECT en FROM MainTopic en ORDER BY ?0";
		if(logger.isDebugEnabled()){
			logger.debug("pageN=" + pageN + " pageSize=" + pageSize + " sortBy=" + sortBy);
		}
		return findByPage(hql, pageN, pageSize, sortBy);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MainTopic> getMainTopicsByForumIds(List<Forum> forums,int pageN_personalHomepage,int pageSize, String sortBy) {
		StringBuffer hql_ = new StringBuffer();
		hql_.append("SELECT en FROM MainTopic en WHERE en.forum.forumId=");
		int j=0;
		for(; j<forums.size(); j++){
			hql_.append("?" + j + " " + "OR");
		}

		String hql = hql_.toString().substring(0, hql_.length()-2);
		hql = hql + " ORDER BY ?" +j;
		
		Query query = getSessionFactory().getCurrentSession().createQuery(hql);
		int i=0;
		for(int len=forums.size(); i<len; i++){
			query.setParameter(i+"", forums.get(i).getForumId());
		}
		query.setParameter(i+"",sortBy);
		List<MainTopic> mainTopics = (List<MainTopic>)query.setFirstResult((pageN_personalHomepage - 1)* pageSize)
				.setMaxResults(pageSize).list();
		return mainTopics;
	}
}
